import { Component } from '@angular/core';
import { IonicPage, NavController, PopoverController, NavParams } from 'ionic-angular';
import { CustomerService } from '../../providers/providers';
import { Utils } from '../../providers/providers';

const PAGE_SIZE: number = 10;

@IonicPage()
@Component({
  selector: 'page-customer-list',
  templateUrl: 'customer-list.html'
})
export class CustomerListPage {

  private param: any;
  private items: any = [];
  private infiniteScroll: any;
  private refresher: any;

  constructor(public navCtrl: NavController, public navParams: NavParams,
    public utils: Utils, public customerService: CustomerService, public popoverCtrl: PopoverController) {
    this.param = {
      customTypeId: navParams.data.customTypeId || '',
      tradeTypeId: navParams.data.tradeTypeId || '',
      telOrId: navParams.data.telOrId || '',
      pageNum: 1,
      length: PAGE_SIZE,
      top: '',
      down: '',
      downId:''
    }
  }

  ionViewDidLoad() {
    this.queryByCondition();
  }

  query(isRefresh?) {
    let copyParam = {};
    for (let k in this.param) {
        copyParam[k] = (isRefresh && k == 'pageNum') ? 1 : this.param[k];
    };

    this.customerService.queryCustList(copyParam)
    .subscribe((res) => {

      this.utils.hideLoading();
      this.refresher && this.refresher.complete();
      this.infiniteScroll && this.infiniteScroll.complete();

      if(res.success && res.data.length > 0) {
        // 刷新操作
        if(isRefresh) {
          this.items = [];
          this.param.pageNum = 1;
        };
        Array.prototype.push.apply(this.items, res.data);
        this.param.pageNum ++;

        // 数据加载完毕
        if(res.data.length < PAGE_SIZE) {
          this.infiniteScroll && this.infiniteScroll.enable(false);
          this.utils.showAlert('加载完毕');
        }
      } else {
        this.infiniteScroll && this.infiniteScroll.enable(false);
      }
    });
  }

  loadMore(infiniteScroll) {
    this.infiniteScroll = infiniteScroll;
    this.query();
  }

  doRefresh(refresher?) {
    this.refresher = refresher;
    this.infiniteScroll && this.infiniteScroll.enable(true);
    this.query(true);
  }

  // 根据条件查询
  queryByCondition() {
    this.utils.showLoading();
    this.doRefresh();
  }


  deleteItem(index) {
    this.utils.confirm('确定删除吗？')
    .then(() => {
      this.items.splice(index, 1);
    });
  }

  clickItem(item) {
    this.navCtrl.push('CustomerViewPage', {
      custId: item.custId
    });
  }

}
